<?php
class Tv_Arte_Tree_Std_Builder extends Tv_Arte_Tree_ABuilder
{
    /**
     * create
     *
     * @static
     * @param   Array $parentId
     * @param   Array $options
     * @return  Tv_Arte_Tree_Std_Builder
     */
    public static function create(Array $dp, $parentId, $options=Array())
    {
        $tmp = Array();
        foreach ($dp as &$value) {
            array_push($tmp, new Tv_Arte_Tree_Std_Data($value));
        } unset($value);
        $dp = $tmp;
        $builder = new Tv_Arte_Tree_Std_Builder($dp);
        if (isset($options['openId'])) {
            $builder->openId($options['openId']);
        }
        $builder->build($parentId);
        return $builder;
    }
    /**
     * build
     * @param Integer $id
     * @return Tv_Arte_Tree_Std_Builder
     */
    public function build($id)
    {
        $this->_composite = new Tv_Arte_Tree_Composite();
        $this->_build($id, $this->_composite);
        return $this;
    }
    /**
     * _hasChildren
     * @param Tv_Arte_Tree_Std_Data $current
     * @return Boolean
     */
    private function _hasChildren($current)
    {
       foreach ($this->_dp as $key => $value) {
           if ($current->getId() == $value->getParentId()) {
               return true;
           }
       }
       return false;
    }
    /**
     * _build
     * @param Integer $id
     * @param Tv_Arte_Tree_AComponent $composite
     * @param Integer $depth
     */
    private function _build($id, Tv_Arte_Tree_AComponent &$composite, $depth=0)
    {
        foreach ($this->_dp as $key => $value) {/* @var $value Tv_Arte_Tree_IComponentData */
            if ($this->_validComponent($id, $value)) {
                $component = ($this->_hasChildren($value)) ? new Tv_Arte_Tree_Composite() : new Tv_Arte_Tree_Leaf();
                $composite->add($component);
                $component->setComponentData($value);
                $value->setDepth($depth + 1);
                $this->_build($value->getId(), $component, $depth + 1);
            }
        }
    }
}